import React from 'react';
import { connect } from 'react-redux';
import { Level2Navigator,
         Paper,
         PaperTitle,
         PaperContent,
         PaperFooter,
         BasicTable,
         SwitchDate,
         } from '../components/dumb';
import { Tabs } from '../components/smart';
import moment from 'moment';

import { ChartsBar, ChartsBarHorizon, ChartsPie, ChartsPolar } from '../components/smart/charts';
import { ListPagesTurnButton } from '../components/smart';

import { switchHomeWorkView,
         getAssignmentTable, 
         getAssignmentChartsFrequency,
         getAssignmentChartsAverage,
         getAssignmentChartsDifficulty,
         getAssignmentChartsQuestion,
         getAssignmentChartsPeriod,
         getAssignmentChartsTimeround,
         getAssignmentDetailTable,
         setAssignmentDetailTableCurrentPageIndex,
         setAssignmentDetailTablePageIndex,
          } from '../actions/homeWorkManagement';
import Filter from './Filter';

import { CITY, COUNTY, SCHOOL } from '../../../constants/area';
import { ASSIGNMENT, CORRECTION } from '../../../constants/homeWorkManagement';

function getPageIndex(arr) {
  return Math.ceil(arr.length/20);
};
function getPageList(arr, pageIndex){
  return arr.slice((pageIndex-1)*20, pageIndex*20);
};
/**
 * 转换布置周期分布，日期到周
 * @return {[type]} [description]
 */
function date2day(arr){
  if (!arr[0].length)return arr;
  let treeArea = {
    '星期一':0,
    '星期二':0,
    '星期三':0,
    '星期四':0,
    '星期五':0,
    '星期六':0,
    '星期日':0,
    };
  let treeParentArea = {
    '星期一':0,
    '星期二':0,
    '星期三':0,
    '星期四':0,
    '星期五':0,
    '星期六':0,
    '星期日':0,
    };
  let keys = ['星期一','星期二','星期三','星期四','星期五','星期六','星期日'];
  let keyArr = arr[0].map((item,index)=>moment(item,'YYYY-MM-DD').format('dddd'));
      keyArr.map((item,index)=>{
        treeArea[item] += arr[1][index];
        treeParentArea[item] += arr[2][index];
      });
  let area = keys.map((item)=>treeArea[item]),
      parentArea = keys.map((item)=>treeParentArea[item]);
  return [
            ['周一','周二','周三','周四','周五','周六','周日'],
            area,
            parentArea,
            arr[3]
          ];
};
/**
 * 转换数据详情部分数据结构，匹配表格需求
 * @return {[type]} [description]
 */
function changeDataStructure(arr) {
  if (!arr[0][0])return arr;
  let newArr = arr.map((items)=>{
    return items.map((item)=>{
        if (item instanceof Array)
            return item.map((itemChild)=>{
              if (Math.floor(itemChild) == itemChild) 
                {
                  return itemChild;
                } else {
                  if (itemChild >=10 )
                    {
                      return Math.round(itemChild);
                    } else {
                      return itemChild.toFixed(1);
                    }
                }
          }).join(' : ');
        return item;
    })
  })
  
  return newArr;
}
/**
 * [getAera 获取当前区域的最下级地域]
 * @param  {[type]} props [状态属性]
 * @return {[type]}       [description]
 */
function getAera(props) {
  let { filter }=props;

  if (filter.school.selectedItem.name){
    return 'school'
  } else if (filter.county.selectedItem.name){
    return 'county'
  } else {
    return 'city'
  }
};
/**
 * 获取当前地域
 * @param  {[type]} city   [description]
 * @param  {[type]} county [description]
 * @param  {[type]} school [description]
 * @return {[type]}        [description]
 */
function getAdressLable(city, county, school) {
  let arr = [city.selectedItem, county.selectedItem, school.selectedItem];
  return arr.map((item) => {
    if (item)
      return item.name;
    else
      return '';
  }).join('')
}
/**
 * [根据筛选器刷新页面]
 * @param  {[type]} props [获取props]
 * @param  {[type]} area  [获取当前地域信息]
 * @return {[type]}       [description]
 */
function getData( props, area, desc, orderBy, timespan){
  let { dispatch, filter, homeWorkManagement } = props;
  let { view } = homeWorkManagement;
  let cityDetailParams,countyDetailParams;

  /**
   * 获取基础表格数据
   * @type {[type]}
   */
  let { city, county, school, dateRange, subject, grade } =filter;
  /**
   * [filterSelectedItems 提取筛选项共用部分]
   * @type {Object}
   */
  let filterSelectedItems = {
    startDate: dateRange[0],
    endDate: dateRange[1],
    subjects: subject.selectedItems,
    grades: grade.selectedItems,
    timespan:timespan||30,
    group:'grade'
  }

  let cityParams = {
    cityId: city.selectedItem.enum,
    provinceName: city.selectedItem.parentName,
    cityName: city.selectedItem.name,
    provinceId: city.selectedItem.parentId,
  }
  Object.assign(cityParams,filterSelectedItems)
  
  let countyParams = {
    countyId: county.selectedItem.enum,
    cityName: city.selectedItem.name || county.selectedItem.parentName,
    countyName: county.selectedItem.name,
    cityId: city.selectedItem.enum || county.selectedItem.parentId
  }
  Object.assign(countyParams,filterSelectedItems)

  let schoolParams = {
    schoolId: school.selectedItem.enum,
    countyName:  county.selectedItem.name ||school.selectedItem.parentName,
    schoolName: school.selectedItem.name,
    countyId: county.selectedItem.enum || school.selectedItem.parentId
  }
  Object.assign(schoolParams,filterSelectedItems)
  if (orderBy) {
    cityDetailParams = Object.assign({},cityParams,{
      desc:desc,
      orderBy,
    });
    countyDetailParams = Object.assign({},countyParams,{
      desc:desc,
      orderBy,
    })
  }
  /**
   * [switch 根据不同地域请求不同数据]
   * @param  {[type]} area [地域类型]
   * @return {[type]}      [description]
   */
  switch (area) {
    case 'city':
      /**
       * [if 当目前为批改作业时不请求基础视图相关数据]
       * @param  {[type]} view [当前视图]
       * @return {[type]}      [description]
       */
      if (view == CORRECTION){
       
        
        if (orderBy) {
            
        } else {
          
        }
        return;
      }
      /**
       * 请求作业管理视图数据
       */
      if (orderBy){
         dispatch(getAssignmentDetailTable('city',cityDetailParams))
      }else {
        dispatch(getAssignmentTable('city', cityParams));
        dispatch(getAssignmentChartsFrequency('city', cityParams))
        dispatch(getAssignmentChartsAverage('city', cityParams))
        dispatch(getAssignmentChartsDifficulty('city', cityParams))
        dispatch(getAssignmentChartsQuestion('city', cityParams))
        dispatch(getAssignmentChartsPeriod('city', cityParams))
        dispatch(getAssignmentChartsTimeround('city', cityParams))
        dispatch(getAssignmentDetailTable('city',cityParams))

      }   
      break;
    case 'county':
      if (view == CORRECTION){
       
        
        if (orderBy) {
              
        } else {
         

        }
        return
      }
      if (orderBy){
        dispatch(getAssignmentDetailTable('county',countyDetailParams))

      }else{
        dispatch(getAssignmentTable('county', countyParams));
        dispatch(getAssignmentChartsFrequency('county', countyParams))
        dispatch(getAssignmentChartsAverage('county', countyParams))
        dispatch(getAssignmentChartsDifficulty('county', countyParams))
        dispatch(getAssignmentChartsQuestion('county', countyParams))
        dispatch(getAssignmentChartsPeriod('county', countyParams))
        dispatch(getAssignmentChartsTimeround('county', countyParams))
        dispatch(getAssignmentDetailTable('county',countyParams))
      }
      break;
    case 'school':
      if (view == CORRECTION){
       
        return
      }
        dispatch(getAssignmentTable('school', schoolParams))
        dispatch(getAssignmentChartsFrequency('school', schoolParams))
        dispatch(getAssignmentChartsAverage('school', schoolParams))
        dispatch(getAssignmentChartsDifficulty('school', schoolParams))
        dispatch(getAssignmentChartsQuestion('school', schoolParams))
        dispatch(getAssignmentChartsPeriod('school', schoolParams))
        dispatch(getAssignmentChartsTimeround('school', schoolParams))
      break;
    default:

  }
}
export default class HomeWorkManagement extends React.Component {
  static propTypes = {
    name: React.PropTypes.string,
  };

  constructor(props) {
    super(props);
  };

  lv2Items = [{
    ID: ASSIGNMENT,
    label:'布置作业'
  },{
    ID: CORRECTION,
    label:'批改作业'
  }];
  /**
   * 获取当前筛选条件下图表数据
   * @return {[type]} [description]
   */
  getCurrentData = (desc,orderBy,timespan) => {
    // 定时器设置延迟，目的是获取最新store
    let timer = setTimeout(() => {
      let props = this.props;
      let area = getAera(props);
      getData(props, area, desc, orderBy, timespan)
      clearTimeout(timer)
    }, 0)
  };

/**
   * [componentWillReceiveProps 状态改变时写入数据详情页码]
   * @param  {[type]} nextProps [description]
   * @return {[type]}           [description]
   */
  componentWillReceiveProps (nextProps) {
    let { dispatch, homeWorkManagement } = nextProps;
    let { assignmentDetailTable, view } = homeWorkManagement;
    let pageIndex = getPageIndex(assignmentDetailTable.dataSource);
    let oldPageIndex = 1;
    if ( view == CORRECTION ) {
     
    } else {
      pageIndex = getPageIndex(assignmentDetailTable.dataSource);

      oldPageIndex = this.props.homeWorkManagement.assignmentDetailTable.pageIndex;
      if ( pageIndex ==  oldPageIndex )return;

      dispatch(setAssignmentDetailTablePageIndex(pageIndex));
      dispatch(setAssignmentDetailTableCurrentPageIndex(1));
    };
  }

  componentWillMount() {
    this.getCurrentData()
  };
  /**
   * 数据详情翻页
   * @return {[type]} [description]
   */
  handleSwitchPageList = (pageIndex) => {
    let { dispatch, homeWorkManagement } = this.props;
    let { view } = homeWorkManagement;
    if ( view == CORRECTION ) {
     
    } else {
      dispatch(setAssignmentDetailTableCurrentPageIndex(pageIndex)) 
    };
  };

  handleSwitchView = (view) => {
    let { dispatch } = this.props;
    dispatch(switchHomeWorkView(view))

  };

  handleFilterChange = (timespan) => {
    this.getCurrentData(false , '', timespan);
      this.setState({
        timespan
      });
  };

  state = {
    descTea:true,
    descHom:true,
    descAve:true,
    descFre:true,
    timespan:30
  };
  handleDetailSort = (item) => {
    let arr = ['地域','布置教师数','作业总量','作业平均题量','教师周布置频次','题目难度分布','题型分布'];
    let { descTea, descHom, descAve, descFre, timespan } = this.state;
    switch (item) {
      case '布置教师数' :
      {
        this.setState({
          descTea:!descTea,
          descHom:true,
          descAve:true,
          descFre:true
        });
        this.getCurrentData(this.state.descTea,'teacher',timespan);
        break;
      };
      case '作业总量' :
      {
        this.setState({
          descTea:true,
          descHom:!descHom,
          descAve:true,
          descFre:true
        });
        this.getCurrentData(this.state.descHom,'homework',timespan);
        break;
      };
      case '作业平均题量' :
      {
        this.setState({
          descTea:true,
          descHom:true,
          descAve:!descAve,
          descFre:true
        });
        this.getCurrentData(this.state.descAve,'average',timespan);
        break;
      };
      case '教师周布置频次' :
      {
        this.setState({
          descTea:true,
          descHom:true,
          descAve:true,
          descFre:!descFre
        });
        this.getCurrentData(this.state.descFre,'frequency',timespan);
        break;
      };
      default:

    }
  }

  render() {
    let { level3Navigator, homeWorkManagement, filter } = this.props;
    let { assignmentTable, assignmentDetailTable, assignmentCharts } = homeWorkManagement;
    let { frequency, average, difficulty, question, period, timeround } = assignmentCharts;
    let assignmentBasicTableHeader = {
          textArray:['地域','布置教师数','作业总量','作业总题量','教师周布置频次','作业平均题量'],
          isDesc:[false,false,false,false,false,false]
        },
        assignmentDetailTableHeader = {
          textArray:['地域','布置教师数','作业总量','作业平均题量','教师周布置频次','题目难度分布','题型分布'],
          isDesc:[false,true,true,true,true,false,false]
        };

    let Tablables =['教师周布置频次', '作业平均题量分布', '题目难度分布', '题目类型分布', '布置周期分布', '布置时段分布'];
    /**
     * [charts 图表组件数组]
     * @type {Array}
     */
    let charts =[ <ChartsBar data={frequency.dataSource} yAxisName={'作业次数'}/>,
                  <ChartsBar data={average.dataSource} yAxisName={'作业平均题量'}/>,
                  <div>
                    <ChartsBarHorizon data={difficulty.dataSource[0]} name={difficulty.dataSource[2][0]||''}/>
                    <ChartsBarHorizon data={difficulty.dataSource[1]} name={difficulty.dataSource[2][1]||''} color={['#feebb2','#fde290','#fdd764','#fcc622']}/>
                  </div>,
                  <div>
                    <ChartsPie />
                    <ChartsPie color={({dataIndex})=>dataIndex==0?'#fcc622':'#ffe38d'}/>
                  </div>,
                  <ChartsBar data={date2day(period.dataSource)} isScale={true} yAxisName={'作业布置次数每日占比'}/>,
                  <div><ChartsPolar data={timeround.dataSource[1]} name={timeround.dataSource[3][0]}/><ChartsPolar color={'#fcc622'} data={timeround.dataSource[2]} name={timeround.dataSource[3][1]}/></div>];    


    
    let { subject, grade, dateRange, city, county, school } = filter;
    /*排序数组*/
    let { descTea, descFre, descHom, descAve } = this.state;
    let orderFlag = [false, descTea, descHom, descAve, descFre, false, false];

    let { view } = homeWorkManagement;
    let { subView } = level3Navigator;
    /*获取各级地域名*/
    let address = getAdressLable(city,county,school);
    return (
      <div>
        <Level2Navigator items={this.lv2Items} selectedItem={view} 
          onChange={this.handleSwitchView} />
        <Filter hasDateSelector={false} hasSwitchDate={true} subView={subView} onFilterChange={this.handleFilterChange} />
        {view == ASSIGNMENT&& 
          <Paper>
            <PaperTitle>
              <div >
                <span><b>{address}布置作业概况</b></span>
              </div>
            </PaperTitle>
            <PaperContent >
              <BasicTable data={assignmentTable.dataSource} tableHeader={assignmentBasicTableHeader} isBackgroundColor={false} />
            </PaperContent>
          </Paper>}
          {view == ASSIGNMENT&& 
            <Paper>
            <PaperTitle>
              <div >
                <span><b>{address}布置作业分布</b></span>
              </div>
            </PaperTitle>
            <PaperContent >
              <Tabs Tablables={Tablables} charts={charts}/>
            </PaperContent>
          </Paper>}
          {view == ASSIGNMENT&& subView != SCHOOL &&
            <Paper>
              <PaperTitle>
                <div >
                  <span><b>数据详情</b></span>
                </div>
              </PaperTitle>
              <PaperContent >
                <BasicTable data={changeDataStructure(getPageList(assignmentDetailTable.dataSource, assignmentDetailTable.currentPageIndex))} 
                    onDetailSort={this.handleDetailSort}
                    orderFlag = {orderFlag}
                    tableHeader={assignmentDetailTableHeader} 
                    isBackgroundColor={true}
                    fontSize={'13px'} />
              </PaperContent>
              <PaperFooter>
                <ListPagesTurnButton pageIndex={assignmentDetailTable.pageIndex} onPaging={this.handleSwitchPageList} currentPageIndex={assignmentDetailTable.currentPageIndex}/>
              </PaperFooter>
            </Paper>}
          
      </div>
    );
  }
}
export default connect((state)=>state)(HomeWorkManagement)